//
//  PlantViewController.m
//  植物管理
//
//  Created by liujianlong on 2022/11/21.
//

#import "PlantViewController.h"
#import "PlantCell.h"
#import "EditViewController.h"

@interface PlantViewController ()
@property (strong, nonatomic) IBOutlet UIImageView *nodataImg;
@property (strong, nonatomic) IBOutlet UIButton *addBtn;
@property (strong, nonatomic) NSMutableArray <Plant *>*array;
@end

@implementation PlantViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loaddata];
    
    [NotifyTool add:self :@selector(loaddata) :notifyPlantUpdate];
}
- (void)initUI{
    self.title = LS(@"花记");
    self.collectionView.c_edges.equalTo(self.view);
    [self.collectionView registerNib:[PlantCell nib] forCellWithReuseIdentifier:[PlantCell ID]];
    self.nodataImg.image = [UIImage imageNamed:LS(@"无数据")];
    [self.view bringSubviewToFront:self.nodataImg];
    [self.view bringSubviewToFront:self.addBtn];
}
- (void)loaddata{
    [PlantTool find:^(NSMutableArray<Plant *> * _Nonnull result) {
        self.array = [NSMutableArray arrayWithArray:result];
        self.nodataImg.hidden = self.array.count > 0;
        [self.collectionView reloadData];
    }];
}
- (IBAction)actionForBtn:(UIButton *)sender {
    EditViewController *vc = [EditViewController new];
    [self push:vc :YES];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.array.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PlantCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[PlantCell ID] forIndexPath:indexPath];
    cell.model = self.array[indexPath.row];
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    EditViewController *vc = [EditViewController new];
    vc.model = self.array[indexPath.row];
    [self push:vc :YES];
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat w = (SCREEN_WIDTH - 60) / 2;
    return  CGSizeMake(w, 212 / 158.0 * w);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(20, 20, 20, 20);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
@end
